package com.decent.ejfadmin.user.service.impl;


import cn.decent.component.shiro.dao.AdminDao;
import cn.decent.component.shiro.entity.Admin;
import cn.decent.component.shiro.service.AdminService;
import cn.decent.component.shiro.util.DesUtil;
import cn.decent.component.shiro.util.SecurityUtil;
import cn.decent.component.shiro.vo.AdminVO;
import com.decent.ejfadmin.common.bean.AdminInterface;
import com.decent.ejfadmin.common.bean.MessageBean;
import com.decent.ejfadmin.common.bean.Page;
import com.decent.ejfadmin.common.exception.OperateFailException;
import com.decent.ejfadmin.user.dao.AdminInterfaceDao;
import com.decent.ejfadmin.user.service.AdminInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 交接班
 *
 * @author weicx
 * @date 2018/07/26
 */
@Service
@Slf4j
public class AdminInterfaceImpl implements AdminInterfaceService {
    @Autowired
    private AdminInterfaceDao adminInterfaceDao;
    @Autowired
    private AdminService adminService;
    @Autowired
    private AdminDao adminDao;

    /**
     * 新增交接班内容
     *
     * @param adminInterface 交接班实体
     * @return
     */
    @Override
    public MessageBean contentIn(AdminInterface adminInterface) {
        try {
            if (adminInterfaceDao.insertContent(adminInterface) != 1) {
                return MessageBean.fail();
            }
        } catch (Exception e) {
            if (e.getMessage().contains("\"CONTENT\"") || e.getMessage().contains("LONG")) {
                MessageBean mb = MessageBean.fail("内容过长");
                mb.setBean(e.getMessage());
                return mb;
            }
            if (e.getMessage().contains("\"TITLE\"")) {
                MessageBean mb = MessageBean.fail("标题过长");
                mb.setBean(e.getMessage());
                return mb;
            }
            log.warn("新增交接内容异常{}", e, e);
            return MessageBean.fail();
        }
        return MessageBean.success();
    }

    /**
     * 修改交接班内容
     *
     * @param adminInterface 交接班实体
     * @return
     */
    @Override
    public MessageBean updateContent(AdminInterface adminInterface) {
        try {
            if (adminInterfaceDao.updateContent(adminInterface) != 1) {
                return MessageBean.fail();
            }
        } catch (Exception e) {
            if (e.getMessage().contains("\"CONTENT\"") || e.getMessage().contains("LONG")) {
                MessageBean mb = MessageBean.fail("内容过长");
                mb.setBean(e.getMessage());
                return mb;
            }
            if (e.getMessage().contains("\"TITLE\"")) {
                MessageBean mb = MessageBean.fail("标题过长");
                mb.setBean(e.getMessage());
                return mb;
            }
            log.warn("修改交接内容异常", e);
            return MessageBean.fail();
        }
        return MessageBean.success();

    }


    /**
     * 首页查询交接班列表
     *
     * @return
     */
    @Override
    public List<AdminInterface> queryTitle(Integer adminType) throws Exception {
        Admin admin = adminService.getCurrentAdmin();
        List<AdminInterface> list = adminInterfaceDao.queryTitle(adminType);
        for (AdminInterface adminInterface : list) {
            if (StringUtils.isNotBlank(adminInterface.getReadAdmin()) &&
                    adminInterface.getReadAdmin().contains(admin.getName())) {
                //已读
                adminInterface.setReadStatus(0);
            } else {
                adminInterface.setReadStatus(1);
            }
        }
        return list;
    }

    /**
     * 标为已读
     *
     * @param id 交接id
     * @return
     */
    @Override
    public MessageBean readerInsert(String adminName, Integer id) {
        AdminInterface adminInterface = adminInterfaceDao.queryContentById(id);
        if (StringUtils.isNotBlank(adminInterface.getReadAdmin())) {
            if (!adminInterface.getReadAdmin().contains(adminName)) {
                adminInterface.setReadAdmin(adminInterface.getReadAdmin() + "," + adminName);
            } else {
                return MessageBean.fail("已经标记过！");
            }
        } else {
            adminInterface.setReadAdmin(adminName);
        }
        if (adminInterfaceDao.updateReadAdmin(adminInterface) != 1) {
            return MessageBean.fail("标记失败！");
        }
        return MessageBean.success();
    }

    /**
     * 分页查询交接班内容
     *
     * @param page           分页组件
     * @param startTime      开始时间
     * @param endTime        结束时间
     * @param adminInterface 交接实体
     * @return
     */
    @Override
    public Page queryTitleList(Page page, String startTime,
                               String endTime, AdminInterface adminInterface) {
        int total = adminInterfaceDao.queryTitleListCount(startTime, endTime, adminInterface);
        page.setTotal(total);
        if (total == 0) {
            page.setResultList(new ArrayList<>());
        } else {
            List<AdminInterface> adminInterfaceList = adminInterfaceDao.queryTitleList(page, startTime, endTime, adminInterface);
            adminInterfaceList.forEach(adminInterfaceBean -> {
                if (StringUtils.isBlank(adminInterfaceBean.getBindRoleIds())) {
                    return;
                }
                List<String> roleNameList = adminInterfaceDao.queryBindRoleNameByRoleId(adminInterfaceBean.getBindRoleIds());
                adminInterfaceBean.setBindRoleNames(String.join(",", roleNameList));
            });
            page.setResultList(adminInterfaceList);
        }
        return page;
    }

    /**
     * 根据id查询交接内容
     *
     * @param id 交接实体
     * @return
     */
    @Override
    public AdminInterface queryAdminByid(Integer id) {
        return adminInterfaceDao.queryContentById(id);
    }

    /**
     * 查询当前管理员是否有未读的交接内容
     *
     * @return
     */
    @Override
    public Boolean queryClose() throws Exception {
        Admin admin = adminService.getCurrentAdmin();
        List<AdminInterface> list = adminInterfaceDao.queryTitle(admin.getRoleId());
        for (AdminInterface adminInterface : list) {
            if (StringUtils.isNotBlank(adminInterface.getReadAdmin())) {
                if (!adminInterface.getReadAdmin().contains(admin.getName())) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 修改密码
     *
     * @param oldPwd 旧密码
     * @param newPwd 新密码
     * @return
     * @throws Exception
     */
    @Override
    public MessageBean modifyAdminPwd(String oldPwd, String newPwd) throws Exception {
        AdminVO currentAdmin = adminService.getCurrentAdmin();
        String realPwd = DesUtil.decrypt(currentAdmin.getLoginPwd(), DesUtil.CHARSET, currentAdmin.getSalt());
        if (!StringUtils.equals(realPwd, oldPwd)) {
            return MessageBean.fail("原密码错误");
        }
        String salt = SecurityUtil.getRandomStr(8);
        String encryptedPwd = DesUtil.encrypt(newPwd, DesUtil.CHARSET, salt);
        currentAdmin.setLoginPwd(encryptedPwd);
        currentAdmin.setSalt(salt);
        adminDao.updatePassword(currentAdmin);
        SecurityUtils.getSubject().logout();
        return MessageBean.success();
    }

    /**
     * 重置用户登录密码
     *
     * @param phoneNo 手机号码
     * @return
     */
    @Override
    public String resetUserLoginPwd(String phoneNo) {
        AdminVO currentAdmin = new AdminVO();
        currentAdmin.setPhoneNo(phoneNo);
        String salt = SecurityUtil.getRandomStr(8);
        currentAdmin.setSalt(salt);
        String pwd = org.apache.commons.lang.RandomStringUtils.random(2, true, false).toUpperCase() + org.apache.commons.lang.RandomStringUtils.random(2, true, false).toLowerCase() + org.apache.commons.lang.RandomStringUtils.random(2, "0123456789") + org.apache.commons.lang.RandomStringUtils.random(2, "!@#$%&*_+>./?,-=");
        String encryptedPwd = DesUtil.encrypt(pwd, DesUtil.CHARSET, salt);
        currentAdmin.setLoginPwd(encryptedPwd);
        if (adminDao.updatePassword(currentAdmin) == 0) {
            throw new OperateFailException("重置用户密码失败");
        }
        return pwd;
    }
}
